package operator.condition;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import util.RxJavaHelper;

class DefaultIfEmptyOperator {

    public static void main(String[] args) {
//        defaultIfEmpty();
        switchIfEmpty();
    }

    /**
     * 如果原始Observable没有发射任何数据正常终止（以onComplete的形式），
     * DefaultIfEmpty返回的Observable就发射一个你提供的默认值
     */
    static void defaultIfEmpty() {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> observableEmitter) throws Exception {
//                observableEmitter.onNext(1);
                observableEmitter.onComplete();
//                observableEmitter.onError(new RuntimeException("123"));
            }
        }).defaultIfEmpty(5)
                .subscribe(RxJavaHelper.getConsumer());
    }


    static void switchIfEmpty() {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> observableEmitter) throws Exception {
//                observableEmitter.onNext(1);
                observableEmitter.onComplete();
//                observableEmitter.onError(new RuntimeException("123"));
            }
        }).switchIfEmpty(Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> observableEmitter) throws Exception {
                observableEmitter.onNext(10);
                observableEmitter.onComplete();
            }
        }))
                .subscribe(RxJavaHelper.getConsumer());
    }

}
